import java.io.*;
import java.util.Scanner;

public class Test4 {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        System.out.println("请输入您要搜索的目录");
        String dir = scanner.next();
        File dirFile = new File(dir);
        if(!dirFile.isDirectory()){
            System.out.println("您输入的不是目录");
            return;
        }
        System.out.println("请输入关键字");
        String keyWord = scanner.next();
        scan(dirFile,keyWord);
    }

    private static void scan(File dirFile, String keyWord) {
        File[] files = dirFile.listFiles();
        if(files == null){
            return;
        }
        for (File file:files) {
            if(file.isFile()){
                dealFile(file,keyWord);
            }else {
                scan(file,keyWord);
            }
        }
    }

    private static void dealFile(File file, String keyWord) {
        if(file.getName().contains(keyWord)){
            System.out.println("找到了文件"+file.getAbsolutePath()+"名字包含关键字");
        }
        StringBuilder stringBuilder = new StringBuilder();
        try(Reader reader = new FileReader(file)) {
            while (true){
                char[] chars = new char[1024];
                int n = reader.read(chars);
                if(n == -1){
                    break;
                }
                stringBuilder.append(chars);
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        if(stringBuilder.indexOf(keyWord) >= 0){
            System.out.println("文件包含关键字"+file.getAbsolutePath());
        }
        return;
    }
}
